<?php

if (!defined('IN_XLP')) {
    exit('Access Denied!');
}

/**
 * Description of newsAction
 *
 * @author xlp
 */
class newsAction extends commonAction {

    function __construct() {
        parent::__construct();
        $this->newsClassify = array('素材库', '便民政策', '社区新闻', '常用号码', '资讯');
        $this->newsType = array(1 => '单条图文', 2 => '<span class="red">多条图文</span>');
        $this->newsStatus = array(1 => '正常', 0 => '<span class="red">受限</span>');
        $this->numberType = array(1 => '警务室', 3 => '社区医院');
    }

    function index() {
        parent::_checkLogin();
        $p = $this->_getid('p');
        $tid = $this->_getid('tid', 0);
        $act = $this->_get('act', 'index');
        $where = array('cid' => 20);
        if ($tid) {
            $where['tid'] = $tid;
        } else {
            $where['tid'] = 0;
        }
        $newsType = M('article_class')->where(array('aid' => admin::$adminInfo['aid']))->order('father_id asc,px desc,tid desc')->findAll();
        if ($newsType) {
            foreach ($newsType as $val) {
                $this->newsClassify[$val['tid']] = $val['catname'];
            }
        }
        $rs = M('article')->where($where)->page($p)->order('px desc,id desc')->findAll();
        $total = M('article')->getTotal();
        $result = array();
        if ($rs) {
            foreach ($rs as $key => $val) {
                $result[$key]['id'] = $val['id'];
                if ($val['type'] == 2) {//多条图文时
                    $result[$key]['type'] = 'more';
                    $result[$key]['header'] = $val;
                    $rsItem = M('article')->field('id,title,description,picurl,infotime')->where(array('fid' => $val['id']))->order('id asc')->limit(0, 7)->findAll();
                    if ($rsItem) {
                        $result[$key]['items'] = $rsItem;
                    }
                } else {
                    $result[$key]['type'] = 'one';
                    $result[$key]['header'] = $val;
                }
            }
        }
//        z($result);
        $this->assign(array('rs' => $result, 'p' => $p, 'total' => $total, 'newsType' => $this->newsType, 'newsStatus' => $this->newsStatus));
        $this->assign(array('tid' => $tid, 'newsClassify' => $this->newsClassify, 'act' => $act));
        $this->display();
    }

    function detail() {
        $id = $this->_getid('id');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('article')->where(array('id' => $id))->find();
        if (!$rs) {
            showError('文章不存在或已删除');
        }
        jumpTo(U('weixin/news/detail', array('id' => $id)));
        if ($rs && isHave($rs['url']) && !isHave($rs['content'])) {
            $url = strExists($rs['url'], 'content/') ? str_replace('content/', 'weixin/', $rs['url']) : $rs['url'];
            jumpTo($url);
            exit;
        }
        $this->assign('rs', $rs);
        $this->display();
    }

//编辑新闻
    function edit() {
        parent::_checkLogin();
        $id = $this->_getid('id');
        if (!$id) {
            showError('参数丢失');
        }
        $rs = M('article')->where(array('aid' => admin::$adminInfo['aid'], 'id' => $id))->find();
        if ($rs) {
            $objData = array();
            $objData['id'] = $rs['id'];
            $objData['tid'] = $rs['tid'];
            if ($rs['type'] == 2) {//多条图文时
                $objData['fid'] = $rs['id'];
                $objData['type'] = 'more';
                $objData['header'] = $rs;
                $rsItem = M('article')->field('id,title,author,is_putin,picurl,content,url')->where(array('fid' => $rs['id']))->order('infotime desc')->limit(0, 7)->findAll();
                if ($rsItem) {
                    $objData['items'] = $rsItem;
                }
//                array_unshift($objData['items'], $rs);
            } else {
                $objData['fid'] = 0;
                $objData['type'] = 'one';
                $objData['header'] = $rs;
            }
        }
//        z($objData);
        $this->assign(array('rs' => $objData));
        $news_cate = D('newsCategory')->get_option($rs['cid']);
        $this->assign('news_cate', $news_cate);

        if ($objData['type'] == 'one') {
            $this->display('edit_one');
        } else {
            $this->display('edit_more');
        }
    }

    /*
     * 管理小区常用号码
     */

    function number() {
        parent::_checkLogin();
        $rs = M('article')->where(array('aid' => admin::$adminInfo['aid'], 'village_id' => admin::$adminInfo['village_id'], 'tid' => 3))->find();
        if ($rs) {
            $rs = json_decode($rs['content'], true);
        }
//        z($rs);
        $this->assign(array('rs' => $rs, 'numberType' => $this->numberType));
        $this->display('number');
    }

    function savenumber() {
//        z($_POST);
        $tid = 3;
        $data = $this->_post('data');
        if (!$data || !is_array($data)) {
            $data = array();
        }
        $data = json_encode($data);
        $rs = M('article')->where(array('aid' => admin::$adminInfo['aid'], 'village_id' => admin::$adminInfo['village_id'], 'tid' => $tid))->find();
        if ($rs) {//更新
            M('article')->update(array('content' => $data), array('aid' => admin::$adminInfo['aid'], 'village_id' => admin::$adminInfo['village_id'], 'tid' => $tid));
        } else {
            $objData['tid'] = $tid;
            $objData['fid'] = 0;
            $objData['aid'] = admin::$adminInfo['aid'];
            $objData['village_id'] = admin::$adminInfo['village_id'];
            $objData['title'] = $this->newsClassify[$tid];
            $objData['author'] = admin::$adminInfo['username'];
            $objData['is_putin'] = 0;
            $objData['type'] = 1;
            $objData['description'] = ''; //摘要
            $objData['picurl'] = ''; //图片
            $objData['url'] = ''; //来源URL
            $objData['status'] = 1;
            $objData['infotime'] = TIME;
            $objData['content'] = $data;
            M('article')->insert($objData);
        }
        $this->JsonReturn('ok', null, 1);
    }

    //添加单条图文
    function add() {
        parent::_checkLogin();
        $tid = $this->_getid('tid', 0);
        // if (!isset($this->newsClassify[$tid])) {
        //     $newsClassify = M('article_class')->field('tid,catname')->where(array('aid' => admin::$adminInfo['aid'], 'tid' => $tid))->find();
        //     if ($newsClassify) {
        //         $this->newsClassify = array();
        //         $this->newsClassify[$newsClassify['tid']] = $newsClassify['catname'];
        //     }
        // }
        $this->assign(array('tid' => $tid));
        $news_cate = D('newsCategory')->get_option();
        $this->assign('news_cate', $news_cate);
        $this->display('add_one');
    }

    //添加多条图文
    function addmore() {
        parent::_checkLogin();
        $tid = $this->_getid('tid', 0);
        $this->assign(array('newsClassify' => $this->newsClassify, 'tid' => $tid));
        $this->display('add_more');
    }

    //上传图片
    function postpic() {
        if (!isHave($_POST['s_auth']) || !isHave($_POST['s_saltkey'])) {
            echo json_encode(array('result' => 'error', 'msg' => '验证失败'));
            exit;
        } else {
            admin::getLoginUser(null, array('auth' => $_POST['s_auth'], 'saltkey' => $_POST['s_saltkey']));
        }
        parent::_checkLogin();
        load('upload');
        $myUpload = new Myupload();
        $upload = $myUpload->upload('news/u' . admin::$adminInfo['aid']);
        $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
        if ($upload) {
            $upload = $upload[0];
            if (!$upload) {
                echo json_encode(array('result' => 'error', 'msg' => $myUpload->getErrorMsg()));
            } else {
                echo json_encode(array('fileUrl' => getImgUrl($upload['savepath']), 'fileName' => $upload['realname'], 'savePath' => $upload['savepath']));
            }
        }
    }

    //正常上传
    function upload() {
        if (parent::_checkLogin(true)) {
            load('upload');
            $myUpload = new Myupload();
            $upload = $myUpload->upload('news/u' . admin::$adminInfo['aid']);
            $upload = parent::_sendImageToYunServer($upload); //同步图片到云存储
            if ($upload) {
                $upload = $upload[0];
                if (!$upload) {
                    echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => $myUpload->getErrorMsg()));
                } else {
                    echo json_encode(array('url' => getImgUrl($upload['savepath']), 'fileType' => $upload['type'], 'original' => $upload['realname'], 'state' => 'SUCCESS'));
                }
            }
        } else {
            echo json_encode(array('url' => '', 'fileType' => '', 'original' => '', 'state' => '上传失败'));
        }
    }

    //保存图文信息
    function post() {
        parent::_checkLogin();
        T('content/validate');
        $action = $this->_post('act', 'add');
        $tid = $this->_postid('tid', 0);
        $px = $this->_postid('px', 0);
        $cid = $this->_postid('cid',20);
        $data = $this->_post('data', '', 'trim');
        if (!$data || !is_array($data)) {
            $this->JsonReturn('内容不能为空');
        }
        $mainNewsData = array();
        if (isset($data[0])) {
            $mainNewsData = $data[0];
            unset($data[0]);
        }
        //主新闻处理
        //============
        $objData = array();
        $objData['tid'] = $tid;
        $objData['fid'] = 0;
        $objData['aid'] = admin::$adminInfo['aid'];
        $objData['cid'] = $cid;
        $objData['village_id'] = admin::$adminInfo['village_id'];
        $objData['title'] = $mainNewsData['title'];
        // $objData['author'] = $mainNewsData['author'];
        $objData['is_putin'] = $mainNewsData['isCover'] ? 1 : 0;
        $objData['type'] = $action == 'add' ? 1 : 2;
        $objData['description'] = isHave($mainNewsData['summary']) ? $mainNewsData['summary'] : ''; //摘要
        $objData['picurl'] = $mainNewsData['coverurl']; //图片
        $objData['content'] = parent::_clearFilter($mainNewsData['content']); //正文
        $objData['url'] = parent::_clearFilter($mainNewsData['source_url']); //来源URL
        $objData['status'] = 1;
        $objData['px'] = $px;
        $objData['infotime'] = TIME;
        //内容规则检查
        $validate = array(
            array('title', 'range_length', '标题长度为2-80个字符', 2, 80),
            array('picurl', 'required', '必须上传图片'),
            array('content', 'max_length', '内容长度为必须小于20000个字符', 20000)
        );
        if (!validate::check($validate, $objData)) {
            $this->JsonReturn(validate::getError());
        }
//        print_r($_POST);
//        z($objData);
        $mainNewsId = M('article')->insert($objData);
        //============
        if ($action == 'add') {//添加单条图文
            if ($mainNewsId) {
                $this->JsonReturn('ok', null, 1);
            } else {
                $this->JsonReturn('添加失败');
            }
        } else {
            if (!$mainNewsId) {
                $this->JsonReturn('正文插入失败');
            }
            $itemData = array();
            if ($data && $mainNewsId) {
                $validate = array(
                    array('title', 'range_length', '标题长度为2-80个字符', 2, 80),
                    array('picurl', 'required', '必须上传图片'),
                    array('content', 'max_length', '内容长度为必须小于20000个字符', 20000)
                );
                foreach ($data as $val) {
                    $objData = array(
                        'tid' => $tid,
                        'fid' => $mainNewsId,
                        'aid' => admin::$adminInfo['aid'],
                        'village_id' => admin::$adminInfo['village_id'],
                        'title' => $val['title'],
                        'type' => 2,
                        'author' => $val['author'],
                        'is_putin' => $val['isCover'] ? 1 : 0,
                        'description' => '',
                        'picurl' => $val['coverurl'],
                        'content' => parent::_clearFilter($val['content']),
                        'url' => parent::_clearFilter($val['source_url']),
                        'status' => 1,
                        'px' => 0,
                        'infotime' => TIME,
                    );
                    //内容规则检查
                    if (!validate::check($validate, $objData)) {
                        $this->JsonReturn(validate::getError());
                    }
                    $itemData[] = $objData;
                }
            }
//            print_r($_POST);
//            z($itemData);
            if ($itemData) {
                M('article')->insertAll($itemData);
                $this->JsonReturn('ok', null, 1);
            } else {
                $this->JsonReturn('error');
            }
        }
    }

    //保存修改
    function save() {
//        z($_POST);
        parent::_checkLogin();
        T('content/validate');
        $action = $this->_post('act', 'edit');
        $tid = $this->_postid('tid', 0);
        $data = $this->_post('data', '', 'trim');
        $id = $this->_postid('id', 0);
        $cid = $this->_postid('cid',0);
        $px = $this->_postid('px', 0);
        if (!$id) {
            $this->JsonReturn('参数丢失');
        }
        if (!$data || !is_array($data)) {
            $this->JsonReturn('内容不能为空');
        }
        $rs = M('article')->where(array('aid' => admin::$adminInfo['aid'], 'id' => $id))->find();
        if (!$rs) {
            $this->JsonReturn('内容不存在');
        }
        $mainNewsData = array();
        if (isset($data[0])) {
            $mainNewsData = $data[0];
            unset($data[0]);
        }
        //主新闻处理
        //============
        $objData = array();
        $objData['tid'] = $tid;
        $objData['title'] = $mainNewsData['title'];
        // $objData['author'] = $mainNewsData['author'];
        $objData['cid'] = $cid;
        $objData['is_putin'] = $mainNewsData['isCover'] ? 1 : 0;
        $objData['description'] = isHave($mainNewsData['summary']) ? $mainNewsData['summary'] : ''; //摘要
        $objData['picurl'] = $mainNewsData['coverurl']; //图片
        $objData['content'] = parent::_clearFilter($mainNewsData['content']); //正文
        $objData['url'] = parent::_clearFilter($mainNewsData['source_url']); //来源URL
        $objData['px'] = $px;
        //内容规则检查
        $validate = array(
            array('title', 'range_length', '标题长度为2-80个字符', 2, 80),
            array('picurl', 'required', '必须上传图片'),
            array('content', 'max_length', '内容长度为必须小于20000个字符', 20000)
        );
        if (!validate::check($validate, $objData)) {
            $this->JsonReturn(validate::getError());
        }
       //z($_POST);
        M('article')->update($objData, array('id' => $id));
        //============
        if ($action == 'edit') {//编辑单条图文
            $this->JsonReturn('ok', null, 1);
        } else {
            $itemData = array();
            if ($data) {
                $validate = array(
                    array('title', 'range_length', '标题长度为2-80个字符', 2, 80),
                    array('picurl', 'required', '必须上传图片'),
                    array('content', 'max_length', '内容长度为必须小于20000个字符', 20000)
                );
                foreach ($data as $val) {
                    $objData = array(
                        'tid' => $tid,
                        'title' => $val['title'],
                        'author' => $val['author'],
                        'is_putin' => $val['isCover'] ? 1 : 0,
                        'description' => '',
                        'picurl' => $val['coverurl'],
                        'content' => parent::_clearFilter($val['content']),
                        'url' => parent::_clearFilter($val['source_url'])
                    );
                    //内容规则检查
                    if (!validate::check($validate, $objData)) {
                        $this->JsonReturn(validate::getError());
                    }
                    if ($val['rid']) {
                        M('article')->update($objData, array('id' => $val['rid']));
                    } else {
                        $objData['tid'] = $tid;
                        $objData['fid'] = $id;
                        $objData['aid'] = admin::$adminInfo['aid'];
                        $objData['village_id'] = admin::$adminInfo['village_id'];
                        $objData['type'] = 2;
                        $objData['status'] = 1;
                        $objData['infotime'] = TIME;
                        $objData['px'] = 0;
                        $itemData[] = $objData;
                    }
                }
            }
//            print_r($_POST);
//            z($itemData);
            if ($itemData) {
                M('article')->insertAll($itemData);
                $this->JsonReturn('ok', null, 1);
            }
            $this->JsonReturn('ok', null, 1);
        }
    }

    function delete() {
        /*
         * 注意这里删除的时候还要查找是否有自定义回复的内容
         */
        parent::_checkLogin();
        $id = $this->_postid('id');
        if (!$id) {
            showError('参数丢失');
        }
        M('article')->delete("id IN (" . $id . ") AND aid=" . admin::$adminInfo['aid']);
        M('article')->delete("fid IN (" . $id . ") AND aid=" . admin::$adminInfo['aid']);
        $this->JsonReturn('ok', null, 1);
    }

    /**
     * 分类管理
     */
    public function cate() {
        $page = $this->_get('page') ? $this->_get('page') : '1';
        $keyword = $this->_get('keyword') ? $this->_get('keyword') : '';
        $list = D('newsCategory')->get_list();
        $total = D('newsCategory')->getTotal();

        $this->assign('list', $list);
        $this->assign('total', $total);
        $this->assign('page', $page);
        $this->assign('keyword', $keyword);
        $this->display();
    }


    public function cateAdd() {
        if ($_POST) {
            $data['name'] = $this->_post('name');
            $data['pid'] = $this->_post('pid') ? $this->_post('pid') : 0;
            $data['sort'] = $this->_post('sort');
            $data['is_show'] = $this->_post('is_show');

            $result = D('newsCategory')->add($data);

            if ($result) {
                if ($data['pid'] == 0) {
                    $depth = 1;
                    $path = '0-' . $result . '-';
                } else {
                    $p_cate = M('article_category')->where('`id`=' . $data['pid'])->find();
                    $depth = $p_cate['depth'] + 1;
                    $path = $p_cate['path'] . $result . '-';
                }
            }

            $result = D('newsCategory')->modify($result, array('path' => "$path", 'depth' => $depth));
            if ($result > 0) {
                $this->JsonReturn('添加分类成功', null, 1);
            } else {
                $this->JsonReturn('添加分类失败', null, 0);
            }
            exit;
        }
        $cate = D('newsCategory')->get_list();
        $cate = D('tree')->genTree($cate);
        $cate = D('tree')->genSelectOption($cate);

        $this->assign('cate', $cate);
        $this->display();
    }

     public function ajax() {
        $id = $this->_get('id') ? $this->_get('id') : null;
        $type = $this->_get('type') ? $this->_get('type') : null;

        switch ($type) {
            case 'cateSave': //商品类别名称更改
                $data = array('name' => $this->_get('name'));
                $stat = D('newsCategory')->modify($id, $data);
                break;
            case 'cateDel': //分类
                $data = array('is_del' => 1);
                $stat = D('newsCategory')->modify($id, $data);
                break;
            default:
                $stat = 0;
                break;
        }

        if ($stat > 0) {
            $info = '请求成功';
            $this->JsonReturn($info, null, 1);
        } else {
            $info = '请求失败';
            $this->JsonReturn($info, null, 0);
        }
    }

}
